
$(function () {
    
    var URL = common.url + 'v_1_0',
        getQueryString = common.getUrlParam

    var constData={
        courseid:'',
        class:'',
        endTime:'',
        startTime:'',
        weekday:'',
        isPublic:'',
        CourseValue:[],
        CourseId:[],
        roomvalue:[],
        roomid:[],
        roomcapacity:[],
        roomteachers:[],
        roomstudentC:[],

    }

    var lessonAdd = {
        clazzId     : null,
        contractStudentId   : getQueryString('contractStudentId'),
        teacherId   : null
    }
    localStorage.setItem('contractStudentId', getQueryString('contractStudentId'));

    var querySchedule = {
        gradeId  :  getQueryString('gradeId'),
        courseId :null
    }

    var studentInfo = [localStorage.getItem('studentName'), localStorage.getItem('gender'), localStorage.getItem('birthDay')]

    /* 请求获取学员姓名*/
    getAjax(URL + '/student-lesson/changgui/get-student?contractStudentId='+lessonAdd.contractStudentId, {}, function (data) {
        if(data.code==0){
            $('.ClassName').html(data.data.studentName);
            constData.isPublic=data.data.isPublic;
            selectClass();
        }
    })

    studentInfo.forEach(function (p1, p2) {
        $('.info-cont li[data-g="true"] span').eq(p2).text(p1)
    })

  
    /* 新增排课功能未开放 */
    $('.btns').on('click', '.edit', function () {
        $.toast('功能未开放')
        // window.location.href = 'arrangeDetail.html'
    })
    
    /* 点击切换背景 */
    $('.class-box li').on('click', function () {
        /**
         * d        JSON   [每个班级对应的数据]
         * list     Array  [数据渲染list]
         * weekday  Object [周列表对应的index]
         * cInfo    Object [渲染进页面list]
         */
        var d, list, weekday, cInfo;
        $('#select-teacher').removeClass('teacher-btn')
        if (!$(this).hasClass('on') || $(this).hasClass('oran')) return;
        $('.class-box li.on').removeClass('oran')
        $(this).addClass('oran')


        /* 初始化   */
        //$('.info-cont li[data-g="false"] span').text('')
        $('#select-teacher').off('click')
        lessonAdd.teacherId = null

        /* 填充数据 */
        d = JSON.parse(this.data)
        weekday  = {
            "MONDAY"    :  '周一',
            "TUESDAY"   :  '周二',
            "WEDNESDAY" :  '周三',
            "THURSDAY"  :  '周四',
            "FRIDAY"    :  '周五',
            "SATURDAY"  :  '周六',
            "SUNDAY"    :  '周日'
        }
    
        // $('#Class').html(d.gradeName);
        // $('#Course').html(d.courseName);
        $('#StartTime').html(new Date(d.startTime).Format('hh:mm')+ '-' +new Date(d.endTime).Format('hh:mm')+ ' ' +weekday[d.weekday]);
        $('#select-Address').val('请选择教室');
       
        //教师选择
        if($('#select-Address').val()=='请选择教室'){
            $('#select-Address').addClass('teacher-btn')
            var datalist=JSON.parse($(this)[0].data);
            constData.endTime=new Date(datalist.endTime).Format('hh:mm:ss')
            constData.startTime=new Date(datalist.startTime).Format('hh:mm:ss')
            constData.weekday=datalist.weekday
            selectClasZoom()
        }else{
            //$('#select-teacher').removeClass('teacher-btn')
           // lessonAdd.teacherId = d.teachers[0].teacherId
        }
    })

    
    /* 请求排课年级*/
   

    /*选择年级字段 */
    function selectClass() {
        getAjax(URL + '/student-lesson/changgui/query-grades?isPublic='+constData.isPublic, {}, function (data) {
        if(data.code==0){
            var dataArray=data.data.grades;
            if(dataArray.length>0){
               var value=[],
                    id=[];

               dataArray.map(function (i,v) {
                    value.push(i.name)
                    id.push(i.id)
                })
                $("#Class").picker({
                     toolbarTemplate: '<header class="bar bar-nav">\
                     <button class="button button-link pull-right close-picker">确定</button>\
                     <h1 class="title">请选择班级</h1>\
                     </header>',
                     cols: [
                       {
                         textAlign: 'center',
                         values: value
                       }
                     ],
                    onOpen:function(v){
                    },
                    onClose:function(v){
                        var sub=v.cols[0].activeIndex;
                        console.log(id[sub]);
                        if(v.displayValue!=undefined){
                         $("#Class").val(v.displayValue)
                        }
                        constData.class =id[sub];
                        ClearInfo(1);
                        selectCourse(constData.class);
                    }
                    
                });
            }else{
                    $.toast('没有可选择的年级')
            }
        }
    })

        
    }

    /*选择课程的字段*/
    function selectCourse(ClassId) {
        if(ClassId==undefined){
            return false;
        }
        getAjax(URL + '/student-lesson/changgui/query-courses?gradeId='+ClassId, {}, function (data) {
            if(data.code==0){
                var dataArray=data.data.courses;
                if(dataArray.length>0){
                    constData.CourseValue.splice(0,constData.CourseValue.length);
                    constData.CourseId.splice(0,constData.CourseId.length);
                    dataArray.map(function (i,v) {
                       constData.CourseValue.push(i.name)
                       constData.CourseId.push(i.id)
                    })
                    $("#Course").picker({
                            toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">请选择课程</h1>\
                            </header>',
                            cols: [
                                  {
                                    textAlign: 'center',
                                    values: constData.CourseValue
                                  }
                            ],
                           onOpen:function(v){
                           },
                           onClose:function(v){
                               console.log(v)
                               var sub=v.cols[0].activeIndex;
                               if(v.displayValue!=undefined){
                                $("#Course").val(v.displayValue)
                               }
                               // console.log(id[sub]);
                               // console.log(v.displayValue)
                               constData.courseid = constData.CourseId[sub];
                               getTimeSlot(constData.courseid)
                               ClearInfo(2) 
                           }
                                   
                    });
                }
            }else{
                $.toast('没有可选择的课程')
            }  
        })   
   }





    /* 请求排课时间段 */
    function getTimeSlot(courseId){
        if(courseId==undefined ||courseId=='' ){
            return false;
        }
        getAjax(URL + '/student-lesson/changgui/query-avalible-time-quantum', 'courseId='+courseId, function (data) {
            $('.class-box li').removeClass('on')
            $('.class-box li').removeClass('oran')
            if( data.data.timeQuantums.length<=0){
                 $.toast('没有可选择的上课时间段')
            }else{
                data.data.timeQuantums.forEach(function (v) {
                    var startTime = new Date(v.startTime).Format('hh:mm'),
                        endTime   = new Date(v.endTime).Format('hh:mm'),
                        weekday   = {
                            "MONDAY"    : [0, '周一'],
                            "TUESDAY"   : [1, '周二'],
                            "WEDNESDAY" : [2, '周三'],
                            "THURSDAY"  : [3, '周四'],
                            "FRIDAY"    : [4, '周五'],
                            "SATURDAY"  : [5, '周六'],
                            "SUNDAY"    : [6, '周日']
                        };
                    $('.left-side li').each(function () {
                        var index = $(this).index();

                        if ($(this).text() == startTime+endTime) {

                            var li = $('.class-box ul').eq(index).find('li').eq(weekday[v.weekday][0])
                            /* 显示班级 */
                            li.addClass('on')
                            li[0].data = JSON.stringify(v)
                        }
                    })
                })
            }
        })
    }


    /* 老师超过一位，选择老师 */
    function selectTeacher(teas) {
        console.log(teas)
        var value=[],
             id=[];

        teas.map(function (i,v) {
             value.push(i.teacherName)
             id.push(i.teacherId)
         })

         $("#select-teacher").picker({
              toolbarTemplate: '<header class="bar bar-nav">\
              <button class="button button-link pull-right close-picker">确定</button>\
              <h1 class="title">请选择老师</h1>\
              </header>',
              cols: [
                {
                  textAlign: 'center',
                  values: value
                }
              ],
             onOpen:function(v){
             },
             onClose:function(v){
                if(v.displayValue!=undefined){
                  $("#select-teacher").val(v.displayValue)
                }
                 var sub=v.cols[0].activeIndex;
                 lessonAdd.teacherId = id[sub]
             }
             
         });

    }

    /* 请选择教室 */
    function selectClasZoom() {
        ClearInfo(3)
        console.log(constData.courseid)
        getAjax(URL + '/student-lesson/changgui/query-avalible-clazzes?courseId='+constData.courseid+'&startTime='+constData.startTime+'&endTime='+constData.endTime+'&weekday='+constData.weekday, {}, function (data) {
            if(data.code==0){
                var dataArray=data.data.classrooms;
                if(dataArray.length>0){
                        constData.roomvalue.splice(0,constData.roomvalue.length);
                    constData.roomid.splice(0,constData.roomid.length);
                    constData.roomcapacity.splice(0,constData.roomcapacity.length);
                    constData.roomteachers.splice(0, constData.roomteachers.length);
                    constData.roomstudentC.splice(0,constData.roomstudentC.length);

                    dataArray.map(function (i,v) {
                         constData.roomvalue.push(i.name)
                         constData.roomid.push(i.clazzId)
                         constData.roomstudentC.push(i.studentCount)
                         constData.roomteachers.push(i.teachers)
                         constData.roomcapacity.push(i.capacity)
                    })
                    
                    $("#select-Address").picker({
                          toolbarTemplate: '<header class="bar bar-nav">\
                          <button class="button button-link pull-right close-picker">确定</button>\
                          <h1 class="title">请选择上课教室</h1>\
                          </header>',
                          cols: [
                            {
                              textAlign: 'center',
                              values: constData.roomvalue
                            }
                          ],
                         onClose:function(v){
                             if(v.displayValue!=undefined){
                               $("#select-Address").val(v.displayValue)
                             }

                            var sub=v.cols[0].activeIndex;
                            console.log(sub)
                            $('#ClassNumber').html(constData.roomcapacity[sub]);
                            $('#NowNUmber').html(constData.roomstudentC[sub]);
                            lessonAdd.clazzId = constData.roomid[sub];
                            //当前已报名学员数
                            $('#select-teacher').toggleClass('teacher-btn', !constData.roomstudentC[sub]>0)
                            if(constData.roomstudentC[sub]>0){
                                console.log(constData.roomteachers[sub][0].teacherName)
                                console.log(constData.roomteachers[sub][0].teacherId)

                                $('#select-teacher').val(constData.roomteachers[sub][0].teacherName==null?'':constData.roomteachers[sub][0].teacherName);
                                lessonAdd.teacherId = constData.roomteachers[sub][0].teacherId
                            }else{
                                $('#select-teacher').val('请选择老师');
                                console.log(constData.roomteachers[sub])
                                if(constData.roomteachers[sub]!=null){ 
                                     if(constData.roomteachers[sub].length>0){
                                         selectTeacher(constData.roomteachers[sub]);
                                     }else{
                                       $.toast('没有可选择的老师')
                                     }
                                }else{
                                       $.toast('没有可选择的老师')
                                }
                            }
                        } 
                    });
                }
            }
        })     
    }


    /* 点击添加排课 */
    // $('.bot-btns .add-btn')[0].abort = true;
    $('.bot-btns .add-btn').on('click', function () {
        var self = this;
        // if (!this.abort) {
        //     return;
        // }
        // this.abort = false;

        /* 处理没有拿到数据 */
        if(constData.class==''){
             $.toast('请选择年级！')
            return false;
        }
        if(constData.courseid==''){
             $.toast('请选择课程！')
            return false;
        }
        
        if(constData.startTime==''){
             $.toast('请选择上课时间段！')
            return false;
        }
        if (!lessonAdd.clazzId) {
            $.toast('请选择上课教室！')
            return false;
        }
        if (!lessonAdd.teacherId) {
            $.toast('请选择授课老师！')
            return false;
        }
        /* 加入班级 */
        postAjax(URL + '/student-lesson/add', JSON.stringify(lessonAdd) , function (res) {
            if(res.code==0){
                window.location.href='../../index.html#/ArrayCourse/' + res.data.contractId;
            }else{
                $.toast(res.message)
                // self.abort = true;
                return false;
            }
        }, true)
    })

    function ClearInfo(num){
        if(num==1){
            $('#select-Address, #select-teacher').val('');
            $('#StartTime,#ClassNumber,#NowNUmber').html('')
            $('#select-Address, #select-teacher').removeClass('teacher-btn')
            lessonAdd.clazzId=null;
            lessonAdd.teacherId=null;
            $('.flex li').removeClass('on');
            $('.flex li').removeClass('oran');

        }else if(num==2){
            $('#select-Address, #select-teacher').val('');
            $('#StartTime,#ClassNumber,#NowNUmber').html('')
            $('#select-Address, #select-teacher').removeClass('teacher-btn');
            lessonAdd.clazzId=null;
            lessonAdd.teacherId=null;
            $('.flex li').removeClass('on');
            $('.flex li').removeClass('oran');
        }else if(num==3){
            $('#select-teacher,#select-Address').val('');
            $('#ClassNumber,#NowNUmber').html('')
            $('#select-teacher').removeClass('teacher-btn');
            lessonAdd.clazzId=null;
            lessonAdd.teacherId=null;
        }else if(num==4){
            $('#ClassNumber,#NowNUmber').val('')
        }

    }

})